var folia_badge = function() {
  // inject the stylesheet we need for the widget to look pretty
  var l = document.createElement('link');
  l.setAttribute('href','http://folia-widgets.googlecode.com/svn/trunk/css/folia.widget.badge.1.0-min.css');
  l.setAttribute('rel','stylesheet');
  l.setAttribute('type','text/css');
  document.getElementsByTagName('head')[0].appendChild(l); 

  // load the API data and fire the callback
  var x = document.getElementById('folia_badge');
  if (x) {
    var gardener = x.className.replace('gardener-','');
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = 'http://myfolia.com/api/v1/gardeners/' + gardener + '/badge.json?callback=folia_badge.render';
    document.getElementsByTagName('head')[0].appendChild(s);
  }

  function render(data) {
    if (data) {
      // display the badge to the page
      var box = document.createElement('div');
      box.className = "folia-widget-box folia-widget-badge-box";

      var header = document.createElement('div');
      header.className = "folia-header";
      header.appendChild(document.createTextNode('Folia Garden Tracker'));
      box.appendChild(header);

      var profilePicture = document.createElement('img');
      profilePicture.src = data.profile_image_url;
      box.appendChild(profilePicture);

      var name = document.createElement('p');
      name.className = "name";
      var nameLink = document.createElement('a');
      nameLink.href = data.profile_url;
      nameLink.title = "Go to my gardening homepage";
      nameLink.appendChild(document.createTextNode(data.display_name));
      name.appendChild(nameLink);
      box.appendChild(name);

      var location = document.createElement('p');
      location.className = "location";
      location.appendChild(document.createTextNode(data.location));
      box.appendChild(location);

      var counts = document.createElement('p');
      counts.className = "counts";

      var plantingCount = document.createElement('span');
      plantingCount.className = "plantings-count";
      plantingCount.appendChild(document.createTextNode(data.plantings_planted_count));
      counts.appendChild(plantingCount);

      var stashCount = document.createElement('span');
      stashCount.className = "stashes-count";
      stashCount.appendChild(document.createTextNode(data.plantings_stashed_count));
      counts.appendChild(stashCount);

      box.appendChild(counts);

      var linkLine = document.createElement('p');
      linkLine.className = "follow";
      var link = document.createElement('a');
      link.href = data.profile_url;
      link.appendChild(document.createTextNode("Follow my gardening on Folia!"));
      linkLine.appendChild(link);
      box.appendChild(linkLine);

      x.removeChild(document.getElementById('folia_badge_loader'));
      x.appendChild(box);

    }
  }
  return { render:render };
}();